package com.xuan.chatroom.service;

import com.xuan.chatroom.constants.Constant;
import com.xuan.chatroom.mapper.UserMapper;
import com.xuan.chatroom.model.Friend;
import com.xuan.chatroom.model.Result;
import com.xuan.chatroom.model.User;
import com.xuan.chatroom.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private FriendService friendService;

    public Result verify(String username, String password, String headerToken) {
        // 1. 根据用户名查询是否存在user对象
        // 如果存在且密码正确则发放 token
        User user = userMapper.queryByName(username);
        if (user != null && user.getPassword().equals(password)) {
            // 2. 判断当前用户是否已持有令牌或令牌是否过期
            // 若该用户携带有效令牌则返回当前令牌即可
            if (headerToken != null && JwtUtil.parseToken(headerToken) != null) {
                return Result.success(headerToken);
            }

            // 3. 用户之前尚未登录或token已过期,重新生成 token
            Map<String, Object> playLoad = new HashMap<>();
            playLoad.put("id", user.getId());
            playLoad.put("username", user.getUsername());
            String token = JwtUtil.geneToken(playLoad);
            return Result.success(token);
        }

        return Result.fail("账号或密码错误", "");
    }


    public Result register(String username, String password) {
        if (username.length() > 30) return Result.fail("用户名过长，请输入长度小于30的用户名", false);
        try {
            User user = null;
            int result = userMapper.insert(user = new User(-1, username, password));
            if (result == 0) return Result.fail("注册失败", false);
            return Result.success(true);
        } catch (DuplicateKeyException e) {
            log.error(e.getMessage());
            return Result.fail("用户名已存在,注册失败", false);
        }
    }

    public List<User> searchUsers(String username, Integer loginUserId) {
        // 1. 搜索登录用户的好友
        List<Friend> friends = friendService.queryFriendListByUserID(loginUserId);
        friends.add(new Friend(loginUserId, null));

        // 2. 搜索除了 当前登录用户和他的好友 之外的用户
        List<User> users = userMapper.searchUsers(username, friends);
        if (users.isEmpty()) return null;

        return users;
    }
}
